import Toast from './toast.vue'
import Vue from 'vue'

let Constructor = Vue.extend(Toast);

let instance;
let instances = [];
let seed = 1;

const ToastBox = function (options) {
  if (Vue.prototype.$isServer) return;
  options = options || {};
  if (typeof options === 'string') {
    options = {
      context: options
    }
  }
  // 组件初始化时把onClose赋值为一个函数
  let userOnClose = options.onClose;
  let id = 'toast_' + seed;
  seed++;
  options.onClose = function (inst) {
    if (typeof userOnClose === 'function') {
      userOnClose(inst);
      ToastBox.close(id);
    }
  };

  instance = new Constructor({ data: options });
  instance.id = id;
  instance.$mount();
  document.body.appendChild(instance.$el);

  // 此处有一个bug，当好几个toast出现，且各自距顶部的offset不同时会出现重叠的问题
  // 建议在使用时把每个toast的offset统一起来
  let verticalOffset = options.offset || 20;
  instances.forEach(item => {
    let offsetH = item.$el.offsetHeight || 0;
    verticalOffset += offsetH + 16;
  })
  instance.verticalOffset = verticalOffset;

  instance.visible = true;
  instances.push(instance);

  return instance
};

['success', 'warning', 'info', 'error'].forEach(type => {
  ToastBox[type] = options => {
    if (typeof options === 'string') {
      options = {
        context: options
      }
    }
    options.type = type;
    return ToastBox(options)
  }
})

ToastBox.close = function (id) {
  let len = instances.length;
  let index = -1;
  let removedHeight = 0;

  for (let i = 0; i < len; i++) {
    if (id === instances[i].id) {
      index = i;
      // 修正element多个弹窗高度不同导致间距混乱的问题。
      let inst = instances[i];
      removedHeight = inst.$el.offsetHeight;
      instances.splice(i, 1);
      break;
    }
  }

  if (len <= 1 || index === -1 || index > instances.length - 1) return;
  // 照element原来的方法有一个bug，此时removedHeight是被删除元素c的下一个元素n的高
  // 若cH < nH c被删除后，n会与c的上一个元素p的距离会 < 16，甚至会小于0
  // 若cH > nH c被删除后，n会与p的上一个元素p距离会变 > 16。
  // 我们需要提前获取到被删除元素的高度，写在上面的取值里。
  // let removedHeight = instances[index].$el.offsetHeight;
  for (let i = index; i < len - 1; i++) {
    let dom = instances[i].$el;
    dom.style['top'] = parseInt(dom.style['top'], 10) - removedHeight - 16 + 'px';
  }
}

export default ToastBox